package com.fyzk.activity.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.ahwf.dialog.BottomDialog;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.activity.app.App;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.chongzhi.RechargeActivity;
import com.fyzk.activity.dialog.AppDialog;
import com.fyzk.activity.setting.SettingActivity;
import com.fyzk.activity.share.ShareCodeActivity;
import com.fyzk.activity.user.ChangeNickname;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.activity.user.UserCenterTogetherBuyActivity;
import com.fyzk.activity.user.UserCenterZhuihaoActivity;
import com.fyzk.activity.user.UserItemView;
import com.fyzk.activity.user.UserItemView.OnUserItemListener;
import com.fyzk.activity.user.WithdrawActivity;
import com.fyzk.activity.user.accountdetail.AccountStatementActivity;
import com.fyzk.activity.user.coupon.CouponActivity;
import com.fyzk.activity.user.touzhu.CommonBetActivity;
import com.fyzk.activity.user.userinfo.AuthenticationActivity;
import com.fyzk.activity.user.userinfo.ChangePasswordActivity;
import com.fyzk.activity.user.userinfo.PersonalInformationActivityNew;
import com.fyzk.base.BaseFragment;
import com.fyzk.bean.AccountMoneyResponse;
import com.fyzk.bean.CouponCountBean;
import com.fyzk.bean.UserInfoResponse;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.net.Commands;
import com.fyzk.net.PublicMethod;
import com.fyzk.utils.AppUtil;
import com.fyzk.utils.FileUtils;
import com.fyzk.utils.ImageUtils;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.LogUtils;
import com.fyzk.utils.Utils;
import com.fyzk.view.CircleImageView;
import com.fyzk.view.MyScrollView;
import com.fyzk.view.OnRefreshListener;
import com.fyzk.view.PullToRefreshLayout;
import com.fyzk.view.ViewCallBack;
import com.tyjc.lottery.R;
import com.wf.domain.UrlDef;

import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;

import http.Common.CommandUtil;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;

import static android.app.Activity.RESULT_OK;

@ContentView(R.layout.fg_usercenter)
public class UserCenterFragment extends BaseFragment implements OnRefreshListener, BottomDialog.OnEntryClickListener {

    @ViewInject(R.id.usercenter_refresh)
    private PullToRefreshLayout refreshLayout;
    @ViewInject(R.id.usercenter_userinfo_ll)
    private RelativeLayout userInfo_ll;
    @ViewInject(R.id.ll_rechargewithdraw)
    private LinearLayout ll_rechargewithdraw;
    @ViewInject(R.id.user1_username)
    private TextView userName_tv;
    @ViewInject(R.id.user1_tixian_ll)
    private TextView tiXian_ll;
    @ViewInject(R.id.balance)
    private TextView tv_balance;
    @ViewInject(R.id.drawbalance)
    private TextView tv_drawbalance;
    @ViewInject(R.id.user1_chongzhi_ll)
    private TextView chongZhi_ll;
    @ViewInject(R.id.photoUrl)
    private CircleImageView iv_photoUrl;

    @ViewInject(R.id.user1_caipiao_ll)
    private UserItemView myCaiPiao_ll;
    @ViewInject(R.id.user_setting)
    private TextView user_setting;

    @ViewInject(R.id.user_editnickname)
    private TextView user_editnickname;
    private int[] myCaiPiao_icons = {R.drawable.icon_commonbet, R.drawable.icon_chasebet,
            R.drawable.icon_togetherbuy, R.drawable.icon_cheappaper, R.drawable.icon_invitation,
            R.drawable.icon_accountdetail, R.drawable.icon_personalinfo,
            R.drawable.icon_changepsw, R.drawable.icon_feedback, R.drawable.icon_service}; // R.drawable.icon_my_red
    private String[] myCaiPiao_names;

    private AccountMoneyResponse accountMoneyResponse;
    private UserInfoResponse userInfoResponse;

    private String[] mHeadSourceData = new String[]{"我的相册", "拍照"};
    private static final int REQUEST_CODE_PHOTO = 0x1;
    private static final int REQUEST_CODE_CAMERA = 0x2;
    private static final int REQUEST_CODE_CROP = 0x3;

    @ViewInject(R.id.user1_coupon_ll)
    private LinearLayout coupon_btn;    // 优惠券按钮
    @ViewInject(R.id.user1_couponcount_tv)
    private TextView couponCount_tv;    // 优惠券数量

    private MySharedPreferences mySharedPreferences;

    @ViewInject(R.id.usercenter_scrollview)
    private MyScrollView scrollView;

    //客服电话
//    private String servicePhone = "";
    //客服QQ
    private String serviceQQ = "";
    private Bitmap mBitmap;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mySharedPreferences = MySharedPreferences.getInstance();
        serviceQQ = mySharedPreferences.getServiceQQ();
//        servicePhone = mySharedPreferences.getCustomerCalls();

        String arrayQQ = AppUtil.getFormatStr(
                App.getContext().getResources().getString(R.string.service_qq),
                serviceQQ);

//        String arrayPhone = AppUtil.getFormatStr(
//                App.getContext().getResources().getString(R.string.service_phone),
//                servicePhone);

        myCaiPiao_names = new String[]{"普通投注", "追号查询", "合买记录", "优惠券", "推荐有壕礼", "账户明细", "个人信息", "修改密码", arrayQQ/*, arrayPhone*/};
        initView();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        return x.view().inject(this, inflater, container);//xutil注解;
    }

    @Override
    public void onRefresh() {
        if (!AppUtil.isNetworkAvailable(getActivity())) {
            AppToast.getToast().show("网络已断开，请检查网络设置！");
            refreshLayout.refreshFinish(PullToRefreshLayout.REFRESH_FAIL);
            return;
        }
        if (!isLogin) {
            AppToast.getToast().show("尚未登录，请登录");
            refreshLayout.refreshFinish(PullToRefreshLayout.REFRESH_FAIL);
            userName_tv.setText("去登录/注册");
            tv_balance.setText("");
            tv_drawbalance.setText("");
            user_editnickname.setVisibility(View.GONE);
        } else {
            requestLeftMoney();
            requestCouponCount();
        }
    }

    private void initView() {

        refreshLayout.setOnRefreshListener(this);
        myCaiPiao_ll.setNames(myCaiPiao_names);
        myCaiPiao_ll.setIcons(myCaiPiao_icons);
        myCaiPiao_ll.addViews();
        myCaiPiao_ll.setOnUserItemListener(new OnUserItem_MyCaiPiao());
        userName_tv.setOnClickListener(this);
        chongZhi_ll.setOnClickListener(this);
        user_setting.setOnClickListener(this);
        user_editnickname.setOnClickListener(this);
        tiXian_ll.setOnClickListener(this);
        userInfo_ll.setOnClickListener(this);
        iv_photoUrl.setOnClickListener(this);

        coupon_btn.setOnClickListener(this);
        scrollView.setOnScrollChanged(new MyScrollView.OnScrollChanged() {
            @Override
            public void onScroll(ScrollView view, int l, int t, int oldl, int oldt) {
                refreshLayout.setCanPull(view.getScrollY() == 0);
            }
        });

        if (MySharedPreferences.getInstance().getOpenStatus()) {
            myCaiPiao_ll.setVisibility(View.VISIBLE);
            ll_rechargewithdraw.setVisibility(View.VISIBLE);
        }

    }

    boolean isLogin = false;

    @Override
    public void onResume() {
        super.onResume();
        isLogin = mySharedPreferences.getLoginStatus();
        if (!isLogin) {
            userName_tv.setText("去登录/注册");
            tv_balance.setText("");
            tv_drawbalance.setText("");
            user_editnickname.setVisibility(View.GONE);
        } else {
            updateUserViews();
            requestLeftMoney();
            requestUserInfo();
            requestCouponCount();
        }
    }

    //查询用户信息
    private void requestUserInfo() {
        httpPostJson(CommandUtil.USERINFO, Commands.USERINFO, null, false);
    }

    private void unLoginViews() {
        userName_tv.setText("去登录/注册");
        tv_balance.setText("");
        tv_drawbalance.setText("");
        user_editnickname.setVisibility(View.GONE);
        iv_photoUrl.setImageResource(R.drawable.header);
    }

    private void requestLeftMoney() {
        httpPostJson(CommandUtil.ACCOUNT_MONEY, Commands.ACCOUNT_MONEY, null, true);
    }

    private void updateUserViews() {
        if (mySharedPreferences.getAlias().equals("")) {
            userName_tv.setText(mySharedPreferences.getUserName());
        } else {
            userName_tv.setText(mySharedPreferences.getAlias());
        }

        String photoUrl = mySharedPreferences.getPhotoUrl();
        if (!TextUtil.isEmpty(photoUrl)) {
            Glide.with(getContext()).load(photoUrl)
                    .error(R.drawable.header)
                    .into(iv_photoUrl);
        }

        tv_balance.setText(Utils.getPrice(mySharedPreferences.getBalance()));
        tv_drawbalance.setText(Utils.getPrice(mySharedPreferences.getDrawbalance()));
    }

    /**
     * 查询可用优惠券数量
     */
    private void requestCouponCount() {
        httpPostJson(CommandUtil.FINDUSERCOUPONCOUNT, Commands.FINDUSERCOUPONCOUNT, null, false);
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.ACCOUNT_MONEY:
                refreshLayout.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
                accountMoneyResponse = JSON.parseObject(resultBean.getData(),
                        AccountMoneyResponse.class);

                mySharedPreferences.setBalance(PublicMethod
                        .formatBalance(accountMoneyResponse
                                .getBalance()));
                mySharedPreferences.setDrawbalance(PublicMethod
                        .formatBalance(accountMoneyResponse
                                .getDrawbalance()));
                mySharedPreferences.setFreeze(PublicMethod
                        .formatBalance(accountMoneyResponse
                                .getFreeze()));
                tv_balance.setText(Utils.getPrice(mySharedPreferences.getBalance()));
                tv_drawbalance.setText(Utils.getPrice(mySharedPreferences.getDrawbalance()));

                break;
            case CommandUtil.FINDUSERCOUPONCOUNT:
                CouponCountBean bean = JSON.parseObject(resultBean.getData(), CouponCountBean
                        .class);
                try {
                    int couponNum = bean.getCouponNum();
                    if (couponNum > 0) {
                        couponCount_tv.setText("(" + couponNum + ")");
                    } else {
                        couponCount_tv.setText("");
                    }

                } catch (Exception e) {
                    couponCount_tv.setText("");
                }

                break;
            case CommandUtil.USERINFO:
                userInfoResponse = JSON.parseObject(resultBean.getData(), UserInfoResponse.class);
                break;
            case CommandUtil.UPDATEHEAD:
                showToast("上传成功");
                String headUrl = resultBean.getData();
                LogUtils.e("====headUrl====" + headUrl);
                if (headUrl != null) {
                    mySharedPreferences.setPhotoUrl(headUrl);
                    Glide.with(getContext()).load(headUrl)
                            .error(R.drawable.header)
                            .into(iv_photoUrl);
                }
                break;
        }
    }

    @Override
    public void onFailure(int requestCode, String errorcode, String msg) {
        if (errorcode.equals("110003")) {
            mySharedPreferences.setLoginStatus(false);
            unLoginViews();
            refreshLayout.refreshFinish(PullToRefreshLayout.REFRESH_FAIL);
        }
    }

    @Override
    protected void onFailure(int requestCode, String message) {
        switch (requestCode) {
            case CommandUtil.ACCOUNT_MONEY:
                refreshLayout.refreshFinish(PullToRefreshLayout.REFRESH_FAIL);
                break;
            default:
                super.onFailure(requestCode, message);
                break;
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_PHOTO://本地相册获取
                if (resultCode == RESULT_OK) {
                    shearPhoto(data.getData()); // 剪切图片
                }
                break;
            case REQUEST_CODE_CAMERA://相机获取
                if (resultCode == RESULT_OK) {
                    File fileTemp = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
                    Uri photoURI = FileUtils.getUriForFile(getActivity(), fileTemp);
                    shearPhoto(photoURI); // 剪切图片
                }
                break;
            case REQUEST_CODE_CROP:
                if (data != null) {
                    mBitmap = data.getParcelableExtra("data");
                    if (mBitmap != null) {
                        iv_photoUrl.setImageBitmap(mBitmap);
                        httpUpLoadHeadPic(mBitmap);
                    }
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 上传头像接口
     */
    private void httpUpLoadHeadPic(Bitmap mBitmap) {
        ImageUtils.saveImageToSD(mBitmap, 0, getContext());
        String imagePath = ImageUtils.getSavePathName(0);
        File file = new File(imagePath);

        RequestParams params = new RequestParams(UrlDef.HEDA_URL);
        // 使用multipart表单上传文件
        params.setMultipart(true);
        if (file.exists()) {
            params.addBodyParameter("file", file, "image/png");
            params.addBodyParameter("type", "1"); //1用户头像，2晒单图片
            params.addBodyParameter("userno", accountMoneyResponse.getUserno());
        }

        LogUtils.e("====params====" + params.toString());
        httpPostJsonHead(CommandUtil.UPDATEHEAD, params, true);
    }

    @Override
    public void onClick(View arg0) {
        if (!isLogin) {
            actionLogout();
            return;
        }
        Intent intent;
        switch (arg0.getId()) {
            case R.id.user1_tixian_ll:
                withdraw();
                break;
            case R.id.user_setting:
                // 设置
                intent = new Intent(getContext(), SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.user_editnickname:
                // 昵称
                intent = new Intent(getContext(), ChangeNickname.class);
                startActivity(intent);
                break;
            case R.id.user1_chongzhi_ll:
                // 充值
                intent = new Intent(getContext(), RechargeActivity.class);
                startActivity(intent);
                break;
            case R.id.user1_coupon_ll:
                // 优惠券
                intent = new Intent(getActivity(), CouponActivity.class);
                startActivity(intent);
                break;
            case R.id.photoUrl:
                showBottomDialog();
                break;
            case R.id.user1_username:
                if (!MySharedPreferences.getInstance().getLoginStatus()) {
                    AppLotteryInfos.clear();
                    ViewCallBack.getInstance().countDownObjs.clear();
                    ActivityTaskManager.getInstance().closeAllActivity();
                    intent = new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                }
                break;
        }
    }

    private void withdraw() {
        if (userInfoResponse != null && !userInfoResponse.getRealName().equals("") &&
                !userInfoResponse.getIdcard().equals("")) {
            Intent intent = new Intent(getContext(), WithdrawActivity.class);
            intent.putExtra(IntentParamUtils.USERNAME,
                    userName_tv.getText());
            intent.putExtra(IntentParamUtils.REALNAME, userInfoResponse.getRealName());
            startActivity(intent);
        } else if (userInfoResponse == null) {
            requestUserInfo();
        } else {
            AppDialog.getDialog().showPerfectInforDialog(getContext(), new AppDialog.OnAppDialogClickListener() {
                @Override
                public void onSureClick() {
                    Intent intent2 = new Intent(getContext(), AuthenticationActivity.class);
                    intent2.putExtra("userinfo", userInfoResponse);
                    startActivity(intent2);
                }

                @Override
                public void onCancleClick() {
                }
            });
        }
    }

    @Override
    public void onLeftClick() {

    }

    @Override
    public void onCenterClick() {

    }

    @Override
    public void onRightClick() {

    }

    @Override
    public void onRight2Click() {

    }

    class OnUserItem_MyCaiPiao implements OnUserItemListener {

        Intent intent;

        @Override
        public void onUserItem(int itemId) {
            if (!isLogin) {
                actionLogout();
                return;
            }

            switch (itemId) {
                case 0:// 普通订单
                    intent = new Intent(getContext(), CommonBetActivity.class);
                    startActivity(intent);
                    break;
                case 1:// 追号查询
                    intent = new Intent(getContext(), UserCenterZhuihaoActivity.class);
                    startActivity(intent);
                    break;
                case 2:// 合买查询
                    intent = new Intent(getContext(), UserCenterTogetherBuyActivity.class);
                    startActivity(intent);
                    break;
                case 3://优惠券
                    intent = new Intent(getActivity(), CouponActivity.class);
                    startActivity(intent);
                    break;
                case 4://邀请有好礼
                    intent = new Intent(getActivity(), ShareCodeActivity.class);
                    startActivity(intent);
                    break;
                case 5:// 账户明细
                    intent = new Intent(getContext(), AccountStatementActivity.class);
                    startActivity(intent);
                    break;
                case 6:// 个人信息
                    intent = new Intent(getContext(), PersonalInformationActivityNew.class);
                    startActivity(intent);
                    break;
                case 7:// 修改密码
                    intent = new Intent(getContext(), ChangePasswordActivity.class);
                    intent.putExtra(IntentParamUtils.USERNAME, userName_tv.getText());
                    startActivity(intent);
                    break;
                case 8:// 客服QQ
                    connectCustomer(serviceQQ);
                    break;
//                case 9:// 客服电话
//                    call(servicePhone);
//                    break;
            }
        }
    }

    /**
     * 联系客服
     */
    public void connectCustomer(String qq) {
        try {
            String customerUrl = "mqqwpa://im/chat?chat_type=wpa&uin=" + qq;
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(customerUrl)));
        } catch (Exception e) {
            e.printStackTrace();
            showToast("请先安装QQ应用");
        }
    }

    public void actionLogout() {
        AppLotteryInfos.clear();
        ViewCallBack.getInstance().countDownObjs.clear();
        ActivityTaskManager.getInstance().closeAllActivity();
        MySharedPreferences.getInstance().setLoginStatus(false);
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
    }

    private void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    private void showBottomDialog() {
        //若没有授权，会弹出一个对话框（这个对话框是系统的，开发者不能自己定制），用户选择是否授权应用使用系统权限
        BottomDialog mDialog = BottomDialog.newInstance(mHeadSourceData);
        mDialog.show(getChildFragmentManager(), "dialog");
        mDialog.setOnEntryClickListener(this);
    }

    @Override
    public void onEntryClick(int position, String type) {
        if (position == 0) {
            Intent intent_photo = new Intent(Intent.ACTION_PICK, null);
            intent_photo.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(intent_photo, REQUEST_CODE_PHOTO);
        } else if (position == 1) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File fileTemp = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, FileUtils.getUriForFile(getActivity(), fileTemp));
                startActivityForResult(intent, REQUEST_CODE_CAMERA);
            }
        }
    }

    private void shearPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, REQUEST_CODE_CROP);
    }

}
